#include"WorkThread.h"

int WorkThreadInit(struct WorkThread *workthread, int index)
{
    workthread->threadId=0;
    sprintf(workthread->name,"subThread-%d",index);
    workthread->evloop=NULL;
    pthread_mutex_init(&workthread->mutex,NULL);
    pthread_cond_init(&workthread->cond,NULL);
    return 0;
}

void* subThreadRuning(void *arg)
{
    struct WorkThread *workthread = (struct WorkThread *)arg;
    pthread_mutex_lock(&workthread->mutex);
    workthread->evloop = CreateEventInitEx(workthread->name);
    pthread_mutex_unlock(&workthread->mutex);
    pthread_cond_signal(&workthread->cond);
    eventLoopRun(workthread->evloop);
    return NULL;

    // 子线程执行的任务，不需要做额外的操作 ，子线程 要执行的饿任务在eventloop中
}

// 调用workthreadrun是主线程 ,执行subThreadRuning的是子线程
// 这里的设计很巧妙，为啥用条件变量
void workThreadRun(struct WorkThread *workthread)
{
    pthread_create(&workthread->threadId,NULL,subThreadRuning,workthread);
    //阻塞主线程，让当前函数不会直接结束
    // 这里访问了共享资源

    pthread_mutex_lock(&workthread->mutex);
    // 多次判断 阻塞多线程
    while(workthread->evloop==NULL)
    {
        // // pthread_cond_wait()
        // int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
        pthread_cond_wait(&workthread->cond,&workthread->mutex);
    }

    pthread_mutex_unlock(&workthread->mutex);

}